package com.ews.onlineexchange.service.observer;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.enterprise.event.Observes;
import javax.enterprise.event.TransactionPhase;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import javax.websocket.DeploymentException;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.model.TradeStatus;
import com.ews.onlineexchange.service.BulletinService;
import com.ews.onlineexchange.service.SmsService;
import com.ews.onlineexchange.service.qualifier.BestBulletinAgreeEvent;

@Stateless
public class BestBulletinAgreeObserver {
	@Inject
	BulletinService bulletinService;
	@Inject
	SmsService smsService;
	@Inject
	EntityManager entityManager;
	
	
	@Asynchronous
	@Transactional( value = TxType.REQUIRED )
	public void listenBestBulletinAgree(@Observes(during = TransactionPhase.AFTER_SUCCESS)  @BestBulletinAgreeEvent Bulletin bulletin) throws DeploymentException, IOException, URISyntaxException {
		bulletin = entityManager.find(Bulletin.class, bulletin.getId());
		if (bulletin.getTradeStatus().equals(TradeStatus.Waiting)) {
			for (Trade trade : bulletin.getBestTrades()) {
				smsService.addCandidateMessageToSupplier(bulletin.getProjectName(),bulletin.getSerialNumber(),trade.getSupplier());
				StringBuilder title = new StringBuilder();
				title.append("【")
				.append(bulletin.getProjectName())
				.append("】，中选通知");
			}
			smsService.addCandidateMessageToBuyer(bulletin);
			bulletinService.startBuyerBestChooseEvaluationProcess(bulletin);
		}
		
	}
	
}
